﻿using System;
using System.Collections.Generic;
using Opalis.QuickIntegrationKit;
using System.Text;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.Collections;

namespace Active_Directory
{
    [OpalisObject("Get Object Property Values")]
    class getObjectPropertyValues : IOpalisObject
    {
        private ConnectionCredentials credentials;

        [OpalisConfiguration]
        public ConnectionCredentials Credentials
        {
            get { return credentials; }
            set { credentials = value; }
        }

        public void Design(IOpalisDesigner designer)
        {
            designer.AddInput("Object LDAP Path").WithDefaultValue("LDAP://CN=ObjectName,OU=Container,DC=Contoso,DC=Com");
            designer.AddCorellatedData(typeof(ObjectValues));
        }

        public void Execute(IOpalisRequest request, IOpalisResponse response)
        {
            string LDAPPath = request.Inputs["Object LDAP Path"].AsString();
            response.WithFiltering().PublishRange(getValues(LDAPPath));
        }

        private IEnumerable<ObjectValues> getValues(string LDAPPath)
        {
            DirectoryEntry objRootDSE = new DirectoryEntry(LDAPPath,credentials.UserName + "@" + credentials.Domain, credentials.Password);

            foreach (string strAttrName in objRootDSE.Properties.PropertyNames)
            {
                //Multi-Value Property
                if (objRootDSE.Properties[strAttrName].Count > 1)
                {
                    PropertyValueCollection ValueCollection = objRootDSE.Properties[strAttrName];
                    IEnumerator en = ValueCollection.GetEnumerator();

                    while (en.MoveNext())
                    {
                        if (en.Current != null)
                        {
                            yield return new ObjectValues(LDAPPath, strAttrName, en.Current.ToString());
                        }
                    }
                }
                //Single Value Property
                else
                {
                    yield return new ObjectValues(LDAPPath, strAttrName, objRootDSE.Properties[strAttrName].Value.ToString());
                }
            }
        }
    }
}
